const Schema=require('../models/model');
let msg=Schema.MessageModel;
let user= Schema.UserModel;

exports.index=async (ctx, next) => {
   await  ctx.render('main');
}
exports.login=async (ctx,next)=>{//------------------------登录|用户信息获取
    let userinfo=ctx.request.body;
    try {
        let res = await user.findOne(userinfo,{username:1,images:1,_id:1});
        if(res!==undefined){
            ctx.body ={status:200,user:res};
        }else{
            ctx.body ={status:400};
        }
    } catch (err) {
        console.log(err);
    }
}
exports.getmessageall=async (ctx,next)=>{//-------------------------获取所有留言-------------------------
    try {
        let res= await msg.find({}).populate({path:'userId', select: 'username images'}).sort({_id:-1})
        ctx.body ={status:200,msg:res};
    } catch (err){
        ctx.body ={status:400};
        console.log(err);
    }
}
exports.getmessage=async (ctx,next)=>{//-------------------------获取留言-------------------------
    let id=ctx.params.id;   //populate()多表查询
    try {
       let res= await msg.find({userId:id}).populate({path:'userId', select: 'username images'}).sort({_id:-1})
        ctx.body ={status:200,msg:res};
    } catch (err){
        ctx.body ={status:400};
        console.log(err);
    }
}
exports.geteditmessage=async (ctx,next)=>{//-------------------------编辑页获取留言-------------------------
    let id = ctx.params.id;
    try {
        let res=await  msg.findOne({_id:id});
        ctx.body ={status:200,msg:res};
    } catch (err){
        ctx.body ={status:400};
        console.log(err);
    }
}
exports.editmessage=async (ctx,next)=>{//-------------------------编辑留言-------------------------
    let id = ctx.params.id;
    try {
        let res=await  msg.update({//---------------updata()
            _id: id
        },{
            $set:{
                message:ctx.request.body.newmsg,
            }
        });
        ctx.body ={status:200};
    } catch (err){
        ctx.body ={status:400};
        console.log(err);
    }
}
exports.delmessage=async (ctx,next)=>{//-------------------------删除留言-------------------------
   let msgId=ctx.request.body.msgId;
    try {
        let res=await msg.remove({_id:msgId});
        ctx.body ={status:200};
    } catch (err){
        ctx.body ={status:400};
        console.log(err);
    }
}
exports.addmessage=async (ctx,next)=>{//---------------------------添加留言----------------------------------
    let {message,userId}=ctx.request.body;
    try {
        let res=await new msg({userId:userId,message:message}).save();
        ctx.body ={status:200,msgId:res._id};
    } catch (err){
        ctx.body ={status:400};
        console.log(err);
    }
}